import ipaddress
import socket
import os
from scapy.sendrecv import sr
from scapy.layers.inet import IP, TCP

def createIPList(network):
    if not isinstance(network, str):
        network = str(network)
    if '/' in network:
        net4 = ipaddress.ip_network(network)
        ipList = []
        for x in net4.hosts():
            ipList.append(x)
        return ipList
    else:
        return [ipaddress.IPv4Address(network)]

def checkServer(address, port, portTimeout, method = 'connet'):
    if method == "connet":
        s = socket.socket()
        s.settimeout(float(portTimeout))
        try:
            s.connect((address, port))
            s.close()
            return True
        except socket.error:
            s.close()
            return False
        except:
            s.close()
            return "FAIL"
    elif method == "syn":
        try:
            temp = sr(IP(dst=address) /
                      TCP(dport=(int(port)), flags='S'),
                      timeout=2, verbose=False)
            if temp[0].res:
                result = temp[0].res  # temp分回复和无回显
                if (result[0][1].payload.flags) == 'SA':
                    return True
                else:
                    return False
            else:
                return False
        except:
            return 'FAIL'

